# model.py

from datetime import datetime
import threading
import time
from threading import Thread, Event

class TimeModel:
    def __init__(self):
        self.current_time = ""
        self.running = False
        self.lock = threading.Lock()
        self._thread = None
        self._time = ""
        self._stop_event = Event()

    def get_current_time(self):
        with self.lock:
            return self.current_time

    def set_current_time(self, time_str):
        with self.lock:
            self.current_time = time_str

    def update_time(self):
        while not self._stop_event.is_set():
            self._time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            time.sleep(1)
        self._stop_event.clear()
            
    
    def start(self):
        self.running = True
        if self._thread is not None and self._thread.is_alive():  # 如果当前线程还在运行则先停止
            self.stop()
        self._stop_event.clear()
        self._thread = Thread(target=self.update_time)
        self._thread.start()

    def stop(self):
        self.running = False
        self._stop_event.set()
        if self._thread and self._thread.is_alive():
            self._thread.join()
